from typing import Tuple
from model.message.messages import FindNodeMessage, PingMessage, GetPeersMessage, QueryMessage
from src.core.network_manage import NetworkManage
from src.log.logger import setup_logger
from src.rpc.transation_holder import TransactionHolder
from src.utils.utils import gen_info_hash, gen_node_id, gen_transaction_id
import logging

class KRPC:
    """KRPC协议"""
    def __init__(self,network_manage:NetworkManage):
        self.logger: logging.Logger = setup_logger('KRPC')
        self.network_manage: NetworkManage = network_manage
        self.transaction_holder: TransactionHolder = network_manage.transaction_holder

    def send_ping_message(self,address:Tuple[str,int]) -> None:
        message = PingMessage(transaction_id=gen_transaction_id(),node_id=self.network_manage.node_id)
        self.logger.debug(f"发送ping消息: {message} 到 {address}")
        self._send_message(message,address)

    def send_find_node_message(self,address:Tuple[str,int]) -> None:
        message = FindNodeMessage(transaction_id=gen_transaction_id(),node_id=self.network_manage.node_id,target=gen_node_id())
        self.logger.debug(f"发送find_node消息: {message} 到 {address}")
        self._send_message(message,address)

    def send_get_peers_message(self,address:Tuple[str,int],info_hash:bytes=gen_info_hash()) -> None:
        message = GetPeersMessage(transaction_id=gen_transaction_id(),node_id=self.network_manage.node_id,info_hash=info_hash)
        self.logger.debug(f"发送get_peers消息: {message} 到 {address}")
        self._send_message(message,address)
    
    def _send_message(self,message:QueryMessage,address:Tuple[str,int]) -> None:
        if not isinstance(message,QueryMessage):
            self.logger.error(f"消息类型错误: {type(message)}")
            return
        self.transaction_holder.add_transaction(message.transaction_id,message.query_name)
        try:
            self.network_manage.send_message(message.to_bytes(),address)
        except Exception as e:
            self.logger.error(f"发送消息失败: {e}")

    